package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author ck
 * @date 2021/11/13 18:15
 */

@DubboService
public class MovementApiImpl implements MovementApi{

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;
    /**
     * 发布动态
     * @param movement
     */
    @Override
    public String publish(Movement movement) {
        //1、保存动态详情
        try {
            //设置pid
            movement.setPid(idWorker.getNextId("movement"));
            //设置发布时间
            movement.setCreated(System.currentTimeMillis());

            //可以手动设置id也可以让mongodb自动生成id 设置id可以不写
            //ObjectId是生成id的工具类
//        movement.setId(ObjectId.get());
            mongoTemplate.save(movement);
            //2、查询当前用户的好友数据
//            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
//            Query query = Query.query(criteria);
//            List<Friend> friends = mongoTemplate.find(query, Friend.class);
//            //3、循环好友数据，构建时间线数据存入数据库
//            for (Friend friend : friends) {
//                MovementTimeLine movementTimeLine = new MovementTimeLine();
//                movementTimeLine.setMovementId(movement.getId());
//                movementTimeLine.setUserId(friend.getUserId());
//                movementTimeLine.setFriendId(friend.getFriendId());
//                movement.setCreated(System.currentTimeMillis());
//                mongoTemplate.save(movementTimeLine);
//            }
            //把同步处理的方式 改成异步处理
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());



        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }

        return movement.getId().toHexString();
    }

    /**
     * 查看个人所有动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).
                skip((page -1) * pagesize).
                limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageResult(page,pagesize,count,movements);
    }


    /**
     * 查询当前用户好友发布的所有动态
     * @param friendId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> findFriends(Long friendId, Integer page, Integer pagesize) {
        //1、查询好友时间线表
        Criteria criteria = Criteria.where("friendId").in(friendId);
        Query query = Query.query(criteria).skip((page - 1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));;
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id集合
        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //3、根据动态id查询动态详情
        Query query1 = Query.query(Criteria.where("id").in(movementId).and("state").is(1));
        return mongoTemplate.find(query1,Movement.class);
    }

    @Override
    public List<Movement> randomMovements(Integer counts) {
        //1、创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        //2、调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3、获取统计结果
        return results.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pid) {
        Query query = Query.query(Criteria.where("pid").in(pid));
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }

    @Override
    public PageResult findByUserIds(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        if (uid != null){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (state != null){
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);

        query.with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page -1) * pagesize);

        List<Movement> list = mongoTemplate.find(query, Movement.class);

        return new PageResult(page,pagesize,count,list);
    }

    @Override
    public void update(String movementId, int state) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = Update.update("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }
}
